package com.sparrow.utils;

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.regex.Pattern;

import com.sparrow.constant.*;

public class StringUtil {

	/**
	 * 获取安全的JSON字符串
	 * 
	 * @author zhanglizhi
	 * @date 2012-5-12
	 * @version 1.0
	 * @param str
	 * @return
	 */
	public static String getSafeJSONString(String str) {
		if (str == null) {
			return null;
		} else {
			return str.replace("'", "\\'").replace(COMMON.ENTER_TEXT,
					"\\\r\\\n");
		}
	}

	/**
	 * 判断字符是否在一字符数组中
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param array
	 * @param key
	 * @return
	 */
	public static boolean existInArray(String[] array, String key) {
		boolean isExist = false;
		if (array != null) {
			for (int i = 0; i < array.length; i++) {
				if (array[i].equals(key)) {
					isExist = true;
					break;
				}
			}
		}
		return isExist;
	}

	/**
	 * 拆分数组的关键字编码 例如:key1:value1,key2:value2 先对边界字进行编码,以防原码有出来边界字符而无法显示
	 * 该函数代码顺序不能变
	 * 
	 * @author zhanglizhi
	 * @date Apr 9, 2011
	 * @version 1.0
	 * @param str
	 *            需要折分的字符串 格式如:key1:value1,key2:value2
	 * @param onlyDot
	 * @return
	 */
	public static String encodeSplitKey(String str, boolean onlyDot) {
		str = str.replace("#", "#limit");
		if (!onlyDot) {
			str = str.replace(":", "#colon#");
		}
		str = str.replace(",", "#dot#");
		return str;
	}

	/**
	 * 对split拆分数组的关键字解码 解码过程与编码过程相反
	 * 
	 * @author zhanglizhi
	 * @date Apr 9, 2011
	 * @version 1.0
	 * @param str
	 * @param onlyDot
	 * @return
	 */
	public static String decodeSplitKey(String str, boolean onlyDot) {
		if (!onlyDot) {
			str = str.replace("#colon#", ":");
		}
		str = str.replace("#dot#", ",");
		str = str.replace("#limit", "#");
		return str;
	}

	/**
	 * 按字节剪切字符串
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param str
	 * @param len
	 * @return
	 */
	public static String subStringByByte(String str, int len) {
		if (len == -1) {
			return str;
		} else {
			return subStringByByte(str, len, "...");
		}
	}

	/**
	 * 按字节剪切字符串，超过长度显示elide
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param str
	 * @param len
	 * @param elide
	 * @return
	 */
	public static String subStringByByte(String str, int len, String elide) {
		if (str == null) {
			return "";
		}
		byte[] strByte = str.getBytes();
		int strLen = strByte.length;
		if (len >= strLen || len < 1) {
			return str;
		}
		int count = 0;
		for (int i = 0; i < len; i++) {
			int value = strByte[i];
			if (value < 0) {
				count++;
			}
		}
		if (count % 2 != 0) {

			len = (len == 1) ? len + 1 : len - 1;
		}
		return new String(strByte, 0, len) + elide.trim();

	}

	/**
	 * 获取字符串中的img标签
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param str
	 * @return
	 */
	public static String getImageUrlFromString(String str) {
		str = str.toLowerCase();
		int a = str.indexOf("<img");
		int b = str.substring(a).indexOf(">");
		String imageURL = str.substring(a, b);
		a = imageURL.indexOf("src=\"");
		b = imageURL.lastIndexOf("\"");
		imageURL = imageURL.substring(a + 5, b - a - 5).trim();
		return imageURL;
	}

	/**
	 * 通过beanName获取其set方法
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param beanName
	 * @return
	 */
	public static String getSetBeanMethodName(String beanName) {
		return "set" + setFirstByteUpperCase(beanName.trim());

	}

	/**
	 * 通过beanName获取其get方法
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param beanName
	 * @return
	 */
	public static String getGetBeanMethodName(String beanName) {
		return "get" + setFirstByteUpperCase(beanName.trim());

	}

	/**
	 * 设置首字母大写
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param srcString
	 * @return
	 */
	public static String setFirstByteUpperCase(String srcString) {
		return srcString.substring(0, 1).toUpperCase() + srcString.substring(1);
	}

	/**
	 * 设置首字母小写
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param srcString
	 * @return
	 */
	public static String setFirstByteLowerCase(String srcString) {
		return srcString.substring(0, 1).toLowerCase() + srcString.substring(1);
	}

	/**
	 * 获取缩进字符
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param indentCount
	 * @return
	 */
	public static String getIndent(int indentCount) {
		return getIndent(indentCount, null);
	}

	/**
	 * 获取缩进字符不足用c代替
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param indentCount
	 * @param c
	 * @return
	 */
	public static String getIndent(int indentCount, String c) {
		StringBuffer sb = new StringBuffer();
		if (c == null) {
			sb.append("\n");
		}
		for (int i = 0; i < indentCount; i++) {
			if (c == null) {
				sb.append("	");
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * null或""为true 否则为false
	 * 
	 * @author zhanglizhi
	 * @date May 7, 2011
	 * @version 1.0
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(Object str) {
		if (str == null || str.toString().trim().equals("")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取在线QQ字符串
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param qq
	 * @return
	 */
	public static String getOnlineQQ(String qq) {
		return "<a target=blank href=\"http://wpa.qq.com/msgrd?V=1&Uin={0}&Exe=QQ&Site="
				+ Config.getValueInFile(LANGUAGE_CONFIG_KEY.WEBSIT_NAME,
						"zh_cn")
				+ "&Menu=No\"><img border=\"0\" src=\"http://wpa.qq.com/pa?p=1:"
				+ qq + ":1\" alt=\"给我发消息\"></a>";
	}

	/**
	 * 将HTML中的br转换成回车文本
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param html
	 * @return
	 */
	public static String convertHtmlBrToEnterText(String html) {
		return html.toLowerCase().replace("<br/>", COMMON.ENTER_TEXT);
	}

	/**
	 * 将回车文本转换成html中的br
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param text
	 * @return
	 */
	public static String convertEnterTextToHtmlBr(String text) {
		return text.replace(COMMON.ENTER_TEXT, "<br/>");
	}

	/**
	 * 一定是双位数
	 * 
	 * @param b
	 *            byte[]
	 * @return String
	 */
	public static String bytes2HexString(byte[] b) {
		String ret = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toUpperCase();
		}
		return ret;
	}

	/**
	 * 将指定字符串src，以每两个字符分割转换为16进制形式
	 * 
	 * 如："2B44EFD9" �> byte[]{0x2B, 0x44, 0xEF,0xD9}
	 * 
	 * @param src
	 *            String
	 * @return byte[]
	 */
	public static byte[] hexString2Bytes(String src) {
		byte[] tmp = src.getBytes();
		byte[] ret = new byte[tmp.length / 2];
		for (int i = 0; i < tmp.length / 2; i++) {
			byte src0 = tmp[i * 2];
			byte src1 = tmp[i * 2 + 1];
			byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
					.byteValue();
			_b0 = (byte) (_b0 << 4);
			byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
					.byteValue();
			ret[i] = (byte) (_b0 ^ _b1);
		}
		return ret;
	}

	public static boolean isInArray(Object[] array, Object item) {
		if (array == null || array.length == 0) {
			return false;
		} else {
			for (Object object : array) {
				if (item.equals(object)) {
					return true;
				}
			}
			return false;
		}
	}

	/**
	 * 从数组array中排除exceptArray并拼接成数组
	 * 
	 * 用于标签删除时的帖子标签更新
	 * 
	 * @param array
	 * @param joinChar
	 * @param exceptArray
	 * @return
	 */
	public static String join(Object[] array, char joinChar,
			Object[] exceptArray) {

		StringBuffer sb = new StringBuffer();
		for (Object object : array) {
			if (isInArray(exceptArray, object)) {
				continue;
			}
			if (sb.length() > 0) {
				sb.append(joinChar);
			}
			sb.append(object);
		}
		return sb.toString();
	}

	public static String join(Object[] array, char joinChar) {
		StringBuffer sb = new StringBuffer();
		for (Object object : array) {
			if (sb.length() > 0) {
				sb.append(joinChar);
			}
			sb.append(object);
		}
		return sb.toString();
	}

	public static String join(Collection<?> collection, char joinChar) {
		StringBuffer sb = new StringBuffer();
		for (Object object : collection) {
			if (sb.length() > 0) {
				sb.append(joinChar);
			}
			sb.append(object);
		}
		return sb.toString();
	}

	public static String decodeForGet(String text) {
		try {
			return new String(text.getBytes("ISO8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	public static String leftPad(String s, char c, int maxLength) {
		StringBuffer sb = new StringBuffer(s);
		for (int i = s.length(); i < maxLength; i++) {
			sb.insert(0, c);
		}
		return sb.toString();
	}

	/**
	 * 只判断是否匹配 且不做后续处理
	 * 
	 * 例如:判断电子邮件或手机号码是否匹配等
	 * 
	 * @author zhanglizhi
	 * @date 2011-12-25
	 * @version 1.0
	 * @param source
	 * @param regex
	 * @return
	 */
	public static boolean matches(String source, String regex) {
		return Pattern.compile(regex, REGEX.OPTION).matcher(source).find();
	}

}
